<template>
    <div class="banner-management">
        <!-- 搜索和操作区域 -->
        <div class="search-operation">
            <el-card shadow="never">
                <div class="search-form">
                    <el-form :model="searchForm" inline>
                        <el-form-item label="轮播图标题">
                            <el-input v-model="searchForm.title" placeholder="请输入轮播图标题" clearable
                                style="width: 200px" />
                        </el-form-item>
                        <el-form-item label="状态">
                            <el-select v-model="searchForm.is_active" clearable placeholder="请选择">
                                <el-option label="启用" :value="1" />
                                <el-option label="禁用" :value="0" />
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
                            <el-button @click="handleReset" :icon="Refresh">重置</el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </el-card>
        </div>

        <!-- 轮播图列表 -->
        <div class="banner-list">
            <el-card shadow="never">
                <template #header>
                    <div class="table-header">
                        <span>轮播图列表</span>
                        <div>
                            <el-button type="primary" @click="handleCreate" :icon="Plus">添加轮播图</el-button>
                            <el-button @click="handleBatchUpdateOrders" :icon="Sort"
                                :disabled="bannerList.length === 0">
                                批量排序
                            </el-button>
                            <el-button @click="handleBatchDelete" :icon="Delete" :disabled="selectedIds.length === 0">
                                批量删除
                            </el-button>
                        </div>
                    </div>
                </template>

                <el-table :data="bannerList" v-loading="loading" border stripe style="width: 100%"
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" align="center" />
                    <el-table-column prop="banner_id" label="ID" width="80" align="center" />
                    <el-table-column prop="image_url" label="轮播图" width="120" align="center">
                        <template #default="{ row }">
                            <el-image :src="getImageUrl(row.image_url)" :preview-src-list="[getImageUrl(row.image_url)]"
                                fit="cover" style="width: 80px; height: 50px; border-radius: 4px;"
                                :hide-on-click-modal="true">
                                <template #error>
                                    <div class="image-slot">
                                        <el-icon>
                                            <Picture />
                                        </el-icon>
                                        <div style="font-size: 12px; margin-top: 5px;">加载失败</div>
                                    </div>
                                </template>
                                <template #placeholder>
                                    <div class="image-slot">
                                        <el-icon>
                                            <Picture />
                                        </el-icon>
                                        <div style="font-size: 12px; margin-top: 5px;">加载中...</div>
                                    </div>
                                </template>
                            </el-image>
                        </template>
                    </el-table-column>
                    <el-table-column prop="title" label="标题" min-width="150" show-overflow-tooltip />
                    <el-table-column prop="link_url" label="跳转链接" min-width="200" show-overflow-tooltip>
                        <template #default="{ row }">
                            <el-link :href="row.link_url" target="_blank" type="primary" :underline="false">
                                {{ row.link_url || '-' }}
                            </el-link>
                        </template>
                    </el-table-column>
                    <el-table-column prop="sort_order" label="排序" width="100" align="center">
                        <template #default="{ row }">
                            <el-input-number v-model="row.sort_order" :min="0" :max="999" size="small"
                                @change="handleSortChange(row)" controls-position="right" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="status" label="状态" width="100" align="center">
                        <template #default="{ row }">
                            <el-switch v-model="row.status" :active-value="1" :inactive-value="0"
                                @change="handleStatusChange(row)" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="created_at" label="创建时间" width="180">
                        <template #default="{ row }">
                            {{ formatDate(row.created_at) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="150" fixed="right" align="center">
                        <template #default="{ row }">
                            <el-button size="small" type="primary" link @click="handleEdit(row)" :icon="Edit">
                                编辑
                            </el-button>
                            <el-button size="small" type="danger" link @click="handleDelete(row.banner_id)"
                                :icon="Delete">
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页 -->
                <div class="pagination">
                    <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.pageSize"
                        :page-sizes="[10, 20, 50, 100]" :total="pagination.total"
                        layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange" />
                </div>
            </el-card>
        </div>

        <!-- 新增/编辑轮播图对话框 -->
        <el-dialog v-model="formDialogVisible" :title="formTitle" width="500px" destroy-on-close>
            <el-form ref="bannerFormRef" :model="bannerForm" :rules="bannerFormRules" label-width="100px">
                <el-form-item label="轮播图标题" prop="title">
                    <el-input v-model="bannerForm.title" placeholder="请输入轮播图标题" maxlength="50" show-word-limit />
                </el-form-item>
                <el-form-item label="轮播图" prop="image_url">
                    <div style="display: flex; align-items: flex-start; gap: 20px;">
                        <el-upload class="avatar-uploader" :action="uploadAction" :headers="uploadHeaders"
                            :show-file-list="false" :on-success="handleImageSuccess" :before-upload="beforeImageUpload"
                            :on-error="handleImageError">
                            <img v-if="bannerForm.image_url" :src="getImageUrl(bannerForm.image_url)" class="avatar" />
                            <div v-else class="avatar-uploader-icon">
                                <el-icon>
                                    <Plus />
                                </el-icon>
                                <div style="margin-top: 8px; font-size: 12px; color: #666;">点击上传</div>
                            </div>
                        </el-upload>

                        <!-- 显示当前图片URL -->
                        <div v-if="bannerForm.image_url" style="flex: 1;">
                            <div style="font-size: 12px; color: #666; margin-bottom: 8px;">当前图片:</div>
                            <el-input v-model="bannerForm.image_url" placeholder="图片URL" size="small" readonly>
                                <template #append>
                                    <el-button @click="copyImageUrl(bannerForm.image_url)" :icon="DocumentCopy"
                                        size="small">
                                        复制
                                    </el-button>
                                </template>
                            </el-input>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="跳转链接" prop="link_url">
                    <el-input v-model="bannerForm.link_url" placeholder="请输入跳转链接" />
                </el-form-item>
                <el-form-item label="排序" prop="sort_order">
                    <el-input-number v-model="bannerForm.sort_order" :min="0" :max="999" controls-position="right" />
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="bannerForm.status">
                        <el-radio :label="1">启用</el-radio>
                        <el-radio :label="0">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="formDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="formLoading">
                    确定
                </el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
    Search,
    Refresh,
    Plus,
    Edit,
    Delete,
    Sort,
    Picture,
    DocumentCopy
} from '@element-plus/icons-vue'
import {
    getBanners,
    createBanner,
    updateBanner,
    deleteBanner,
    toggleBannerStatus,
    batchUpdateBannerOrders,
    batchDeleteBanners
} from '@/api/banner'

const loading = ref(false)
const formDialogVisible = ref(false)
const formLoading = ref(false)
const bannerFormRef = ref()
const currentBanner = ref(null)
const bannerList = ref([])
const selectedIds = ref([])

// 上传配置
const uploadAction = `${import.meta.env.VITE_API_BASE_URL || 'http://localhost:7001'}/upload/banner-image`
const uploadHeaders = {
    // token: localStorage.getItem('adminToken') || ''
}

// 搜索表单 - 修复：使用后端字段名 is_active
const searchForm = reactive({
    title: '',
    is_active: ''  // 改为使用后端字段名
})

// 分页配置
const pagination = reactive({
    page: 1,
    pageSize: 10,
    total: 0
})

// 轮播图表单
const bannerForm = reactive({
    title: '',
    image_url: '',
    link_url: '',
    sort_order: 0,
    status: 1
})

// 表单验证规则
const bannerFormRules = {
    title: [
        { required: true, message: '请输入轮播图标题', trigger: 'blur' },
        { min: 2, max: 50, message: '标题长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    image_url: [
        { required: true, message: '请上传轮播图', trigger: 'change' }
    ],
    link_url: [
        { required: true, message: '请输入跳转链接', trigger: 'blur' }
    ]
}

// 计算属性
const formTitle = computed(() => {
    return isCreate.value ? '添加轮播图' : '编辑轮播图'
})

const isCreate = computed(() => {
    return !currentBanner.value?.banner_id
})

// 工具函数
const formatDate = (dateString) => {
    if (!dateString) return '-'
    try {
        const date = new Date(dateString)
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        }).replace(/\//g, '-')
    } catch (error) {
        return dateString
    }
}

// 图片URL处理函数
const getImageUrl = (url) => {
    if (!url) return ''

    // 如果已经是完整URL，直接返回
    if (url.startsWith('http')) {
        return url
    }

    // 如果是相对路径，添加基础URL
    const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:7001'

    // 处理不同格式的路径
    if (url.startsWith('/')) {
        return `${baseUrl}${url}`
    } else {
        return `${baseUrl}/${url}`
    }
}

// 图片上传错误处理
const handleImageError = (error) => {
    console.error('图片上传失败:', error)
    ElMessage.error('图片上传失败，请重试')
}

// 复制图片URL功能
const copyImageUrl = async (url) => {
    try {
        await navigator.clipboard.writeText(url)
        ElMessage.success('图片URL已复制到剪贴板')
    } catch (err) {
        console.error('复制失败:', err)
        // 降级方案
        const textArea = document.createElement('textarea')
        textArea.value = url
        document.body.appendChild(textArea)
        textArea.select()
        document.execCommand('copy')
        document.body.removeChild(textArea)
        ElMessage.success('图片URL已复制到剪贴板')
    }
}

// 页面加载时获取轮播图列表
onMounted(() => {
    fetchBanners()
})

// 获取轮播图列表
const fetchBanners = async () => {
    try {
        loading.value = true

        const params = {
            page: pagination.page,
            pageSize: pagination.pageSize,
            ...searchForm
        }

        // 清理空值参数
        Object.keys(params).forEach(key => {
            if (params[key] === '' || params[key] === null || params[key] === undefined) {
                delete params[key]
            }
        })

        console.log('搜索参数:', params) // 调试用

        const response = await getBanners(params)

        if (response.code === 0) {
            // 处理字段映射
            const list = response.data.list || response.data
            bannerList.value = list.map(item => ({
                id: item.banner_id, // 映射 banner_id 到 id
                banner_id: item.banner_id,
                title: item.title,
                image_url: item.image_url,
                link_url: item.link_url,
                sort_order: item.display_order, // 映射 display_order 到 sort_order
                display_order: item.display_order,
                status: item.is_active, // 映射 is_active 到 status
                is_active: item.is_active,
                created_at: item.created_at
            }))

            pagination.total = response.data.pagination?.total || response.data.total || list.length || 0

        } else {
            ElMessage.error(response.msg || '获取轮播图列表失败')
        }
    } catch (error) {
        ElMessage.error('网络错误，请稍后重试')
        console.error('获取轮播图列表失败:', error)
    } finally {
        loading.value = false
    }
}

// 搜索轮播图
const handleSearch = () => {
    pagination.page = 1
    fetchBanners()
}

// 重置搜索
const handleReset = () => {
    Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
    })
    pagination.page = 1
    fetchBanners()
}

// 分页大小改变
const handleSizeChange = (newSize) => {
    pagination.pageSize = newSize
    pagination.page = 1
    fetchBanners()
}

// 当前页改变
const handleCurrentChange = (newPage) => {
    pagination.page = newPage
    fetchBanners()
}

// 选择改变
const handleSelectionChange = (selection) => {
    selectedIds.value = selection.map(item => item.banner_id) // 使用 banner_id
}

// 新增轮播图
const handleCreate = () => {
    currentBanner.value = null
    resetForm()
    formDialogVisible.value = true
}

// 编辑轮播图
const handleEdit = (banner) => {
    currentBanner.value = banner
    Object.keys(bannerForm).forEach(key => {
        if (currentBanner.value[key] !== undefined) {
            bannerForm[key] = currentBanner.value[key]
        }
    })

    // 确保图片URL是原始值，不要处理
    bannerForm.image_url = banner.image_url

    formDialogVisible.value = true
}

// 切换状态
const handleStatusChange = async (banner) => {
    try {
        const response = await toggleBannerStatus(banner.banner_id) // 使用 banner_id
        if (response.code === 0) {
            ElMessage.success(banner.status === 1 ? '启用成功' : '禁用成功')
            // 刷新列表以确保数据同步
            fetchBanners()
        } else {
            // 如果操作失败，回滚状态
            banner.status = banner.status === 1 ? 0 : 1
            ElMessage.error(response.msg || '操作失败')
        }
    } catch (error) {
        // 如果操作失败，回滚状态
        banner.status = banner.status === 1 ? 0 : 1
        ElMessage.error('操作失败')
        console.error('切换状态失败:', error)
    }
}

// 排序改变
const handleSortChange = async (banner) => {
    try {
        const response = await updateBanner(banner.banner_id, { // 使用 banner_id
            display_order: banner.sort_order // 映射到 display_order
        })
        if (response.code === 0) {
            ElMessage.success('排序更新成功')
        } else {
            ElMessage.error(response.msg || '排序更新失败')
        }
    } catch (error) {
        ElMessage.error('排序更新失败')
        console.error('排序更新失败:', error)
    }
}

// 批量排序
const handleBatchUpdateOrders = async () => {
    try {
        const orders = bannerList.value.map(banner => ({
            banner_id: banner.banner_id, // 使用 banner_id
            display_order: banner.sort_order // 映射到 display_order
        }))

        const response = await batchUpdateBannerOrders({ orders })
        if (response.code === 0) {
            ElMessage.success('批量排序成功')
            fetchBanners() // 刷新列表
        } else {
            ElMessage.error(response.msg || '批量排序失败')
        }
    } catch (error) {
        ElMessage.error('批量排序失败')
        console.error('批量排序失败:', error)
    }
}

// 删除轮播图
const handleDelete = async (bannerId) => {
    try {
        await ElMessageBox.confirm(
            '确定要删除该轮播图吗？此操作不可恢复！',
            '警告',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )

        const response = await deleteBanner(bannerId)
        if (response.code === 0) {
            ElMessage.success('删除轮播图成功')
            fetchBanners()
        } else {
            ElMessage.error(response.msg || '删除轮播图失败')
        }
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除轮播图失败')
            console.error('删除轮播图失败:', error)
        }
    }
}

// 批量删除
const handleBatchDelete = async () => {
    if (selectedIds.value.length === 0) {
        ElMessage.warning('请选择要删除的轮播图')
        return
    }

    try {
        await ElMessageBox.confirm(
            `确定要删除选中的 ${selectedIds.value.length} 个轮播图吗？此操作不可恢复！`,
            '警告',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )

        const response = await batchDeleteBanners({
            ids: selectedIds.value
        })

        if (response.code === 0) {
            ElMessage.success('批量删除成功')
            selectedIds.value = []
            fetchBanners()
        } else {
            ElMessage.error(response.msg || '批量删除失败')
        }
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('批量删除失败')
            console.error('批量删除失败:', error)
        }
    }
}

// 图片上传成功
const handleImageSuccess = (response) => {
    console.log('上传响应:', response)

    if (response.code === 0) {
        let imageUrl = ''

        // 处理不同的响应格式
        if (response.data && response.data.url) {
            imageUrl = response.data.url
        } else if (response.data) {
            imageUrl = response.data
        } else if (response.url) {
            imageUrl = response.url
        } else {
            ElMessage.error('无法获取图片URL')
            return
        }

        bannerForm.image_url = imageUrl
        ElMessage.success('图片上传成功')

        // 手动触发表单验证更新
        if (bannerFormRef.value) {
            bannerFormRef.value.validateField('image_url')
        }
    } else {
        ElMessage.error(response.msg || '图片上传失败')
    }
}

// 图片上传前验证
const beforeImageUpload = (file) => {
    console.log('上传文件:', file)

    const isImage = file.type.startsWith('image/')
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isImage) {
        ElMessage.error('只能上传图片文件!')
        return false
    }

    // 检查具体的图片格式
    const allowedTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif']
    if (!allowedTypes.includes(file.type)) {
        ElMessage.error('图片格式必须是 JPG、PNG、WEBP 或 GIF!')
        return false
    }

    if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!')
        return false
    }

    return true
}

// 提交表单（新增/编辑）
const handleSubmit = async () => {
    if (!bannerFormRef.value) return

    try {
        await bannerFormRef.value.validate()
        formLoading.value = true

        // 准备提交数据，映射字段名
        const submitData = {
            title: bannerForm.title,
            image_url: bannerForm.image_url,
            link_url: bannerForm.link_url,
            display_order: bannerForm.sort_order, // 映射 sort_order 到 display_order
            is_active: bannerForm.status // 映射 status 到 is_active
        }

        let response

        if (isCreate.value) {
            // 新增轮播图
            response = await createBanner(submitData)

            if (response.code === 0) {
                ElMessage.success('添加轮播图成功')
                formDialogVisible.value = false
                fetchBanners()
            } else {
                ElMessage.error(response.msg || '添加轮播图失败')
            }
        } else {
            // 编辑轮播图
            response = await updateBanner(currentBanner.value.banner_id, submitData) // 使用 banner_id

            if (response.code === 0) {
                ElMessage.success('更新轮播图成功')
                formDialogVisible.value = false
                fetchBanners()
            } else {
                ElMessage.error(response.msg || '更新轮播图失败')
            }
        }
    } catch (error) {
        if (error.errors) {
            ElMessage.error('请完善表单信息')
        } else {
            ElMessage.error(isCreate.value ? '添加轮播图失败' : '更新轮播图失败')
            console.error('表单提交失败:', error)
        }
    } finally {
        formLoading.value = false
    }
}

// 重置表单
const resetForm = () => {
    Object.keys(bannerForm).forEach(key => {
        if (key === 'sort_order') {
            bannerForm[key] = 0
        } else if (key === 'status') {
            bannerForm[key] = 1
        } else {
            bannerForm[key] = ''
        }
    })

    if (bannerFormRef.value) {
        bannerFormRef.value.clearValidate()
    }
}
</script>

<style scoped>
.banner-management {
    padding: 20px;
}

.search-operation {
    margin-bottom: 20px;
}

.search-form {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.banner-list {
    margin-bottom: 20px;
}

.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.avatar-uploader {
    :deep(.el-upload) {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
        width: 178px;
        height: 100px;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    :deep(.el-upload:hover) {
        border-color: var(--el-color-primary);
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        text-align: center;
        line-height: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }

    .avatar {
        width: 178px;
        height: 100px;
        display: block;
        object-fit: cover;
    }
}

.image-slot {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 80px;
    height: 50px;
    background: #f5f7fa;
    color: #909399;
    font-size: 20px;
    border-radius: 4px;
}
</style>